package com.wmf.listener;

import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.annotation.WebListener;
import javax.servlet.http.HttpSession;
import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener;

@WebListener
public class OnlinePersonCountListener  implements ServletContextListener, HttpSessionListener {
    //创建一个application变量
    ServletContext application = null;

    //监听服务器停止
    @Override
    public void contextDestroyed(ServletContextEvent servletContextEvent) {
        // TODO Auto-generated method stub
        System.out.println("服务器停止，容器销毁");
    }
    //监听服务器启动
    @Override
    public void contextInitialized(ServletContextEvent servletContextEvent) {
        System.out.println("服务器启动，容器创建");
        //网站在线人数
        servletContextEvent.getServletContext().setAttribute("visitcount", 0);
        //登录用户人数
        servletContextEvent.getServletContext().setAttribute("logincount", 0);
    }

    //当浏览器对服务器发起请求，就会创建一个唯一session对象，该session对象是基于服务器端创建的。
    //每当访问一次前端页面，都会创建一个session，并不是统计登录人数的，是统计访问网站人数的
    @Override
    public void sessionCreated(HttpSessionEvent httpSessionEvent) {
        HttpSession session = httpSessionEvent.getSession();
        Integer visitcount = (Integer) session.getServletContext().getAttribute("visitcount");
        visitcount++;
        session.getServletContext().setAttribute("visitcount",visitcount);
        System.out.println("当前共有 "+visitcount+" 位用户在线访问！");
    }


    @Override
    public void sessionDestroyed(HttpSessionEvent httpSessionEvent) {
        //离线
        HttpSession session = httpSessionEvent.getSession();
        Integer visitcount = (Integer) session.getServletContext().getAttribute("visitcount");
        visitcount--;
        session.getServletContext().setAttribute("visitcount", visitcount);
        Integer logincount = (Integer)  session.getServletContext().getAttribute("logincount");
        session.setAttribute("visitcount",logincount-1);
    }
}

